<script setup>
import { ref } from 'vue'
import { addEmpApi, updateEmpApi } from '@/api/EmpApi.js'
import { ElMessage } from 'element-plus'

const form = ref({
  empno: '',
  ename: '',
  job: '',
  deptno: '',
  sal: ''
})
const centerDialogVisible = ref(false)
const init = (row) => {
  if (row) {
    //修改员工信息
    form.value = { ...row }
  } else {
    //添加员工信息
    form.value = {
      empno: '',
      ename: '',
      job: '',
      deptno: '',
      sal: ''
    }

  }
  centerDialogVisible.value = true

}
const rules = {
  ename: [
    { required: true, message: '请输入员工姓名', trigger: 'blur' },
    { min: 2, max: 5, message: '员工姓名长度2-5位', trigger: 'blur' }
  ],
  job: [
    { required: true, message: '请输入职务', trigger: 'blur' },
  ]
}
//
const emit = defineEmits(['success'])
const formRef = ref(null)
const save = () => {
formRef.value.validate(async (valid) => {
  if (valid) {
    //保存员工信息

    if (form.value.empno) {
      //修改员工信息
      await updateEmpApi(form.value)
    } else {
      //添加员工信息
      await addEmpApi(form.value)
    }
    ElMessage({
      type: 'success',
      message: '操作成功'
    })
    centerDialogVisible.value = false
    //清空表单数据resetForm()
    emit('success')
  }
})
}


// *******************暴露方法给父组件调用

defineExpose( {
  init
})
</script>

<template>
  <el-dialog
    v-model="centerDialogVisible"
    :title="form.empno ? '修改员工信息' : '添加员工信息'"
    width="500"
    align-center
  >
    <el-form :model="form"  ref="formRef" :rules="rules" label-width="auto" style="max-width: 600px" >

      <el-form-item label="员工编号">
        <el-input v-model="form.empno" clearable type="text" readonly/>
      </el-form-item>
      <el-form-item label="员工姓名" prop="ename">
        <el-input v-model="form.ename" type="text" clearable />
      </el-form-item>
      <el-form-item label="职务" prop="job">
        <el-input v-model="form.job" type="text" clearable />
      </el-form-item>
      <el-form-item label="部门编号">
        <el-input v-model="form.deptno" type="text" clearable />
      </el-form-item>
      <el-form-item label="薪资">
        <el-input v-model="form.sal" type="text" clearable />
      </el-form-item>
    </el-form>
<!--    <span>Open the dialog from the center from the screen</span>-->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="save">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>

</style>